package com.sunday.authorization.core.userdetails;

import com.sunday.authorization.security.tools.userdetails.UserInfo;
import com.sunday.authorization.security.userdetails.CustomUser;
import com.sunday.boot3.user.center.pojo.dto.user.GetAuthUserReqDTO;
import com.sunday.boot3.user.center.pojo.dto.user.GetAuthUserResDTO;
import com.sunday.boot3.user.center.provider.UserProvider;
import com.sunday.common.core.remoting.base.response.Response;
import com.sunday.common.core.remoting.rpc.response.RPCResponseHandler;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Optional;

/**
 * @Description: 身份验证
 */
@Component
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    @DubboReference
    private UserProvider userProvider;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //单机临时测试类，后续由这里获取账户信息，来源可自行斟酌
        return Optional.ofNullable(getUser(username))
                .map(userDetails -> {
                    CustomUser user = new CustomUser(
                            userDetails.getUsername(),
                            userDetails.getPassword(),
                            new HashSet<>(),
                            UserInfo.builder()
                                    .id(userDetails.getId())
                                    .username(userDetails.getUsername())
                                    .permissionsSum(userDetails.getPermissionsSum())
//                                    .username(username)
//                                    .permissionsSum(PermissionDTOTool.collect(PermissionDTOTool.authorization()))
//                                    .permissionsSum(PermissionDTOTool.collect(PermissionDTOTool.authorization(new HashSet<>(Arrays.asList("/api/blacklist/classify/update")))))
//                                    .permissionsSum(new long[]{Long.MAX_VALUE,Long.MAX_VALUE,Long.MAX_VALUE,Long.MAX_VALUE})
                                    .build());
                    return user;
                })
                .orElseThrow(() -> new UsernameNotFoundException("账户或密码错误"));
    }

    /**
     * 获取用户
     */
    public GetAuthUserResDTO getUser(String username) {
        return Optional.ofNullable(RPCResponseHandler.invoke(() -> userProvider.getAuthUser(new GetAuthUserReqDTO(username))))
                .filter(Response::isSuccess)
                .map(Response::getBody)
                .orElse(null);
    }

}
